#include <stdio.h>

#define N   8

int count = 0;
int set[N];

void prq(int (*q)[N])
{
    int i, j;

    for (i = 0; i < N; i ++) {
        for (j = 0; j < N; j ++) {
            if (q[i][j] == 1)
                printf("Q ");
            else
                printf(". ");
        }
        printf("\n");
    }
    printf("\n");
    count ++;
}

void queen_1(int n, int (*q)[N])
{
    int forbid[N] = {0};
    int i, j;

    if (n > N)
        prq(q);
    
    for (i = 0; i < n-1; i++) 
    {
        for (j = 0; j < N; j++)
        {
            if (q[i][j] == 1)
            {
                forbid[j] = 1;
                if (n-1-i+j < N)
                    forbid[n-1-i+j] = 1;
                if (i+j+1-n >= 0)
                    forbid[i+j+1-n] = 1;
                break;
            }
        }
    }

    for (i = 0; i < N; i++)
    {
        if (forbid[i] == 0)
        {
            q[n-1][i] = 1;
            queen_1(n+1, q);
            q[n-1][i] = 0;
        }
    }
}

int canSet(int i, int j, int (*q)[N])
{
    int a, b;

    for (a = 0; a < i; a ++)
    {
        if (set[a] == j || i-a == j-set[a] || i-a == set[a]-j)
            return 0;
    }
    
    return 1;
}

void queen_2(int (*q)[N])
{
    int i, j, find;

    for (i = 0; i < N; i ++)
    {
        set[i] = -1;
    }

    for (i = 0; i < N; i++) {
        find = 0;

        for (j = 0; j < N; j++) {
            if (j > set[i] && canSet(i, j, q))
            {
                find = 1;
                set[i] = j;
                q[i][j] = 1;

                if (i == N-1)
                {
                    prq(q);
                    q[i][j] = 0;
                    find = 0;
                }

                break;
            }
        }

        if (find == 0)
        {
            if (i == 0)
            {
                printf("%d\n", count);
                return;
            }

            q[i-1][set[i-1]] = 0;
            set[i] = -1;
            i -= 2;
        }
    }
}

int main(int argc, char const* argv[])
{
    int q[N][N] = {{0}};
    queen_1(1, q);
    printf("%d\n", count);

    printf("queen_2\n");
    count = 0;
    queen_2(q);
    return 0;
}
